package com.loren.demo03.springboot;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;

@Component
@RequiredArgsConstructor
public class NettyClient {

    private final NettyProperties nettyProperties;

    private final NettyClientHandler nettyClientHandler;

    private Bootstrap bootstrap;

    @PostConstruct
    public void init() {
        EventLoopGroup group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(this.nettyProperties.getHost(), this.nettyProperties.getPort()))
                .handler(this.nettyClientHandler);
    }

    public void sendMessage(String message) throws InterruptedException {
        ChannelFuture future = bootstrap.connect().sync();
        Channel channel = future.channel();
        channel.writeAndFlush(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8));
        channel.closeFuture();
    }
}
